package controller.search;

import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.DBException;
import model.Employee;
import model.SearchDB;
import model.SessionCheck;

/**
 * Servlet implementation class Search
 */
@WebServlet("/Search")
public class Search extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String disp = "/Search.jsp";

		request.setCharacterEncoding("UTF-8");
		int record_count = 0;
		ArrayList<Employee> employees = new ArrayList<Employee>();

		// セッションのチェック
		SessionCheck sessioncheck = new SessionCheck(request);
		disp = sessioncheck.checksession(disp);

		// 検索処理
		SearchDB searchdb = new SearchDB(request);
		try {
			employees = searchdb.searchresult();
		} catch (DBException e) {
			switch (e.getErrorCode()) {
			case DBException.DB_OPEN_ERR:
				disp = "/DBErr.jsp";
				break;
			case DBException.DB_RESULT_NOTHING:
				disp = "/DBErr.jsp";
				break;
			case DBException.DB_RESULT_NOTREAD:
				disp = "/DBErr.jsp";
				break;
			case DBException.DB_CLOSE_ERR:
				disp = "/DBErr.jsp";
				break;
			}
			String err_msg = e.getMessage();
			System.out.println(err_msg);
		}

		ServletContext sc = getServletContext();
		RequestDispatcher rd = sc.getRequestDispatcher(disp);
		request.setAttribute("count", record_count);
		request.setAttribute("employees", employees);
		rd.forward(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}